﻿using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Windows;
using System.Windows.Controls;
using System.Xml.Linq;
using 立库托盘入库.bean;
using 立库托盘入库.HttpUntil;
using 立库托盘入库.MyInterface;
using 立库托盘入库.Until;

namespace 立库托盘入库.ViewModel
{
    class MainViewModel : INotifyPropertyChanged,MainInterface
    {
        //列表绑定数据
        private ObservableCollection<panItemBean> _mainviewdatas;
        private List<panItemBean> mlist;
        //叉车员工设置dialog显示
        private Visibility _isChacheUsername;
        //绑定叉车dialog
        private ChacheUsernameDialog _chacheUsrnameDialog;
        //选择的叉车员工
        private ObservableCollection<UserBean> _xUsers;
        //搜索出来的叉车员工
        private ObservableCollection<UserBean> _zUsers;
        private static MainViewModel M;
        //选择的串口参数
        private ChuanKouBean _ckbean;
        //设置串口dialog
        private Visibility _isScanDialogOpen;
        //电脑连接到的串口
        private String[] _chuanKous;
        //串口的选择参数
        private ChuankouSettingBean _chuankouSettingBean;
        //绑定刷新动画
        private SettinfScan _SettinfScanContent;
        //可以选择的员工列表
        String[] _usernames;
        //选择的叉车员工
        String _username;
        //刷新动画显示
        private Visibility _isSampleDialogOpen;
        //刷新动画
        private ProgressDialog _sampleDialog;
        //提示文字
        private String _tishi;

        String _portName;
        int _baudRate;
        String _parity;
        int _dataBits;
        String _stopBits;

        private string path;
        private ComUntil mycom;


        public static MainViewModel MainViewModelCreate()
        {
            if (M == null)
            {
                M = new MainViewModel();
                
                return M;
            }
            else
            {
                return M;
            }
        }
        public void initdata()
        {
              
            path = AppDomain.CurrentDomain.BaseDirectory;
            _mainviewdatas = new ObservableCollection<panItemBean>();
            mlist = new List<panItemBean>();
            _ckbean = new ChuanKouBean();
            RaisePropertyChanged("MainViewDatas");
            _xUsers = new ObservableCollection<UserBean>();
            _zUsers = new ObservableCollection<UserBean>();
            _sampleDialog = new ProgressDialog();
            IsSampleDialogOpen = Visibility.Visible;
        }

        public MainViewModel()
        {
            SampleDialog = new ProgressDialog();
            _isSampleDialogOpen = Visibility.Hidden;
        }

        public ComUntil MyCom
        {
            get { return mycom; }
            set
            {
                mycom = value;
            }
        }

        //加载刷新动画显示
        public Visibility IsSampleDialogOpen
        {
            get { return _isSampleDialogOpen; }
            set
            {
                _isSampleDialogOpen = value;
                RaisePropertyChanged("IsSampleDialogOpen");
            }
        }
        //提示文字
        public String Tishi
        {
            get { return _tishi; }
            set
            {
                _tishi = value;
                RaisePropertyChanged("Tishi");
            }
        }

        //加载刷新绑定
        public ProgressDialog SampleDialog
        {
            get { return _sampleDialog; }
            set
            {
                _sampleDialog = value;
                RaisePropertyChanged("SampleDialog");
            }
        }

        //刷新串口
        public void sxcom()
        {
            MyCom.readCOMs(true, path);
        }

        //可以选择的员工
        public String[] UserNames
        {
            get { return _usernames; }
            set
            {
                _usernames = value;
                RaisePropertyChanged("UserNames");
            }
        }
        //选择的叉车员工
        public String UserName
        {
            get { return _username; }
            set
            {
                _username = value;
                RaisePropertyChanged("UserName");
            }
        }

        public void getData()
        {
            IsSampleDialogOpen = Visibility.Visible;
            MyHttpUtil.getHttpPanData(this);
        }
        
        public void getUserData(String username)
        {
            MyHttpUtil.getHttpPda_Username(this, username);
        }

        public void HttpGetPanDataOk(string data)
        {
            System.Windows.Application.Current.Dispatcher.Invoke((Action)(() =>
            {
                IsSampleDialogOpen = Visibility.Hidden;
                jsondata(data);
            }));
        }

        public void HttpGetPanDataNo(string e)
        {
            IsSampleDialogOpen = Visibility.Hidden;
            Debug.WriteLine(e);
        }

        //选择叉车员工dialog
        public ChacheUsernameDialog ChacheUsernameContent
        {
            get { return _chacheUsrnameDialog; }
            set
            {
                _chacheUsrnameDialog = value;
                RaisePropertyChanged("ChacheUsernameContent");
            }
        }
        //选择叉车员工显示
        public Visibility isChacheUsername
        {
            get { return _isChacheUsername; }
            set
            {
                _isChacheUsername = value;
                RaisePropertyChanged("IsChacheUsername");
            }
        }
        //已经选择的叉车员工
        public ObservableCollection<UserBean> XUserBeans
        {
            get { return _xUsers; }
            set
            {
                _xUsers = value;
                RaisePropertyChanged("XUserBeans");
            }
        }
        //待选择的PDA组员工
        public ObservableCollection<UserBean> ZUserBeans
        {
            get { return _zUsers; }
            set
            {
                _zUsers = value;
                RaisePropertyChanged("ZUserBeans");
            }
        }

        //待选择的PDA组员工
        public ChuanKouBean CkBean
        {
            get { return _ckbean; }
            set
            {
                _ckbean = value;
                RaisePropertyChanged("CkBean");
            }
        }

        //设置串口的dialog
        public Visibility IsScanDialogOpen
        {
            get { return _isScanDialogOpen; }
            set
            {
                _isScanDialogOpen = value;
                RaisePropertyChanged("IsScanDialogOpen");
            }
        }

        //电脑连接上的串口
        public String[] ChuanKous
        {
            get { return _chuanKous; }
            set
            {
                _chuanKous = value;
                RaisePropertyChanged("ChuanKous");
            }
        }

        
        //设置dialog绑定
        public SettinfScan SettinfScanContent
        {
            get { return _SettinfScanContent; }
            set
            {
                _SettinfScanContent = value;
                RaisePropertyChanged("SettinfScanContent");
            }
        }

        //串口的选择设置
        public ChuankouSettingBean ChuankouSettingBean
        {
            get { return _chuankouSettingBean; }
            set
            {
                _chuankouSettingBean = value;
                RaisePropertyChanged("ChuankouSettingBean");
            }
        }

        public string PortName
        {
            get { return _portName; }
            set
            {
                _portName = value;
                RaisePropertyChanged("PortName");
            }
        }

        public int BaudRate
        {
            get { return _baudRate; }
            set
            {
                _baudRate = value;
                RaisePropertyChanged("BaudRate");
            }
        }

        public string Parity
        {
            get { return _parity; }
            set
            {
                _parity = value;
                RaisePropertyChanged("Parity");
            }
        }

        public int DataBits
        {
            get { return _dataBits; }
            set
            {
                _dataBits = value;
                RaisePropertyChanged("DataBits");
            }
        }

        public string StopBits
        {
            get { return _stopBits; }
            set
            {
                _stopBits = value;
                RaisePropertyChanged("StopBits");
            }
        }




        public ObservableCollection<panItemBean> MainViewDatas {
            get { return _mainviewdatas; }
        }

        public event PropertyChangedEventHandler PropertyChanged;
        private void RaisePropertyChanged(string PropertyName)
        {
            PropertyChangedEventHandler handler = PropertyChanged;
            if (handler != null)
            {
                handler(this, new PropertyChangedEventArgs(PropertyName));
            }
        }
        public void jsondata(String data)
        {
            if (data == "")
            {
                return;
            }
            Debug.WriteLine(data);
            _mainviewdatas.Clear();
            var jom = (JObject)JsonConvert.DeserializeObject(data);
            var jodata = (JObject)jom["msg"];
            var jsred = (JArray)jodata["rows_red"];
            var jsgreen = (JArray)jodata["rows_green"];
            var jsblue = (JArray)jodata["rows_blue"];
            var jsorange = (JArray)jodata["rows_orange"];
            foreach (JObject jo in jsred)
            {
                var bean = new panItemBean();
                bean.Color = "red";
                bean.PositionBuffer = (String)jo["position_buffer"];
                bean.PalletNum = (String)jo["pallet_num"];
                bean.PcycleId = (String)jo["pcycle_id"];
                bean.WeiWanGong = (String)jo["weiwancheng"];
                bean.YiWanGong = (String)jo["yiwancheng"];
                bean.ZupanTime = (String)jo["zp_ctime"];
                bean.Onum = (String)jo["onum"];
                bean.Isquxiao = Visibility.Visible;
                bean.BufferFinishStatu = (String)jo["buffer_finish_status"];
                bean.BufferShelfStatus = (String)jo["buffer_shelf_status"];
                _mainviewdatas.Add(bean);
            }
            foreach (JObject jo in jsgreen)
            {
                var bean = new panItemBean();
                bean.Color = "green";
                bean.PositionBuffer = (String)jo["position_buffer"];
                bean.PalletNum = (String)jo["pallet_num"];
                bean.PcycleId = (String)jo["pcycle_id"];
                bean.WeiWanGong = (String)jo["weiwancheng"];
                bean.YiWanGong = (String)jo["yiwancheng"];
                bean.ZupanTime = (String)jo["zp_ctime"];
                bean.Onum = (String)jo["onum"];
                bean.Isquxiao = Visibility.Hidden;
                bean.BufferFinishStatu = (String)jo["buffer_finish_status"];
                bean.BufferShelfStatus = (String)jo["buffer_shelf_status"];
                _mainviewdatas.Add(bean);
            }
            foreach (JObject jo in jsblue)
            {
                var bean = new panItemBean();
                bean.Color = "blue";
                bean.PositionBuffer = (String)jo["position_buffer"];
                bean.PalletNum = (String)jo["pallet_num"];
                bean.PcycleId = (String)jo["pcycle_id"];
                bean.WeiWanGong = (String)jo["weiwancheng"];
                bean.YiWanGong = (String)jo["yiwancheng"];
                bean.ZupanTime = (String)jo["zp_ctime"];
                bean.Onum = (String)jo["onum"];
                bean.Isquxiao = Visibility.Hidden;
                bean.BufferFinishStatu = (String)jo["buffer_finish_status"];
                bean.BufferShelfStatus = (String)jo["buffer_shelf_status"];
                _mainviewdatas.Add(bean);
            }
            foreach (JObject jo in jsorange)
            {
                var bean = new panItemBean();
                bean.Color = "orange";
                bean.PositionBuffer = (String)jo["position_buffer"];
                bean.PalletNum = (String)jo["pallet_num"];
                bean.WeiWanGong = (String)jo["weiwancheng"];
                bean.YiWanGong = (String)jo["yiwancheng"];
                bean.ZupanTime = (String)jo["zp_ctime"];
                bean.Onum = (String)jo["onum"];
                bean.Isquxiao = Visibility.Hidden;
                bean.BufferFinishStatu = (String)jo["buffer_finish_status"];
                bean.BufferShelfStatus = (String)jo["buffer_shelf_status"];
                _mainviewdatas.Add(bean);
            }
            //RaisePropertyChanged("MainViewDatas");

        }

        //上传叉车入库记录成功
        public void HttpPostForkliftRecordOk(string data)
        {
            Tishi = UserName+"上传入库数据成功";
            getData();
        }
        //上传叉车入库记录失败
        public void HttpPostForkliftRecordNo(string e)
        {
            MessageBox.Show(unicodezhuan(e));
        }
        //取消叉车入库指令成功
        public void HttpPostFinishCancelOk(string data)
        {
            getData();
        }
        //取消叉车入库指令失败
        public void HttpPostFinishCancelNo(string e)
        {
            MessageBox.Show(unicodezhuan(e));
        }
        //获取PDA组员工成功成功
        public void HttpGetPdaUsernameOk(string data)
        {
            usernamejsondata(data);
        }
        //获取PDA组员工成功失败
        public void HttpGetPdaUsernameNo(string e)
        {
            MessageBox.Show(unicodezhuan(e));
        }
        //取消叉车手动入库指令成功
        public void HttpPostShoudongFinishCancelOk(string data)
        {
            getData();
        }
        //取消叉车手动入库指令失败
        public void HttpPostShoudongFinishCancelNo(string e)
        {
            MessageBox.Show(unicodezhuan(e));
        }

        //解析待获取的员工列表
        public void usernamejsondata(String data)
        {
            if (data == "")
            {
                return;
            }
            _zUsers.Clear();
            var jom = (JObject)JsonConvert.DeserializeObject(data);
            var jsdata = (JArray)jom["msg"];
            foreach (JObject jo in jsdata)
            {
                var bean = new UserBean();
                bean.UserName = (String)jo["name"];
                bean.Uid = (String)jo["uid"];
                bean.IsXuan = isUserX(bean);
                _zUsers.Add(bean);
            }
            //_xUsers.Clear();
            //foreach (UserBean bean in _zUsers)
            //{
            //    if (bean.IsXuan)
            //    {
            //        _xUsers.Add(bean);
            //    }
            //}
            Debug.WriteLine("ZUserBeans");
        }
        //点击选中或者删除叉车司机
        public void isXuanUser(UserBean bean,bool isxuan)
        {
            if (isxuan)
            {
                _xUsers.Add(bean);
            }
            else
            {
                _xUsers.Remove(bean);
            }
            
            foreach (UserBean b in _zUsers)
            {
                if (bean.Uid == b.Uid)
                {
                    b.IsXuan = isxuan;
                }
            }
            //_xUsers.Clear();
            //foreach (UserBean b in _zUsers)
            //{
            //    if (b.IsXuan)
            //    {
            //        _xUsers.Add(b);
            //    }
            //}

            //RaisePropertyChanged("ZUserBeans");
            //RaisePropertyChanged("XUserBeans");
        }
        //判断这个员工是否选择
        public bool isUserX(UserBean bean)
        {
            foreach (UserBean b in _xUsers)
            {
                if (b.Uid == bean.Uid)
                {
                    return true;
                }
            }
            return false;
        }

        //扫描到数据后将数据发送给服务器
        public void scrm_com(string data)
        {
            Tishi = "当前入库操作员："+UserName;
            data = data.Trim();
            String uid = "";
            foreach (UserBean bean in XUserBeans)
            {
                if (bean.UserName == UserName)
                {
                    uid = bean.Uid;
                    break;
                }
            }
            if (uid == "")
            {
                MessageBox.Show("没有选择叉车操作员");
            }
            else
            {
                MyHttpUtil.postHttpForkliftRecord(this, data, uid);
            }
        }

        //取消二楼入库
        public void deletePallte(String pallet_num)
        {
            if (MessageBox.Show("确定取消托盘："+ pallet_num + "二楼入库","提示", MessageBoxButton.YesNo, MessageBoxImage.Information) == MessageBoxResult.Yes)
            {
                MyHttpUtil.postHttpPallet_Finish_Cancel(this, pallet_num);
            }
        }

        //取消手动入库
        public void quxiaoshoudongRuku(String pallet_num)
        {
            if (MessageBox.Show("确定取消托盘：" + pallet_num + "手动完成", "提示", MessageBoxButton.YesNo, MessageBoxImage.Information) == MessageBoxResult.Yes)
            {
                MyHttpUtil.postHttpPallet_Shoudong_Finish_Cancel(this, pallet_num);
            }
        }

        //每十秒运行一次
        public void xunhuan()
        {
            System.Timers.Timer aTimer = new System.Timers.Timer();
            aTimer.Elapsed += new System.Timers.ElapsedEventHandler(dt_Tick);
            aTimer.Interval = 30000;//每二十秒执行一次
            aTimer.Enabled = true;
            void dt_Tick(object sender, EventArgs e)
            {
                getData();
            }
        }

        private String unicodezhuan(String unicode)
        {
            return new Regex(@"\\u([0-9A-F]{4})", RegexOptions.IgnoreCase | RegexOptions.Compiled).Replace(
                 unicode, x => string.Empty + Convert.ToChar(Convert.ToUInt16(x.Result("$1"), 16)));
        }


    }
}
